/**
 * @Description: 模型监控管理
 * @Date: 2020-03-23 11:20:45
 */
$(function () {
    // 重置窗口大小
    function resizeWindow() {
        var DEBUG;
        //DEBUG = true;
        if (DEBUG) {
            [].forEach.call($($('*')), function (a) {
                a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
            });
        }
        var minHeight = $(window).height() - $('#userTable').offset().top - 10;
        $('#dataTreeDiv').css('max-height', minHeight);
    }
    resizeWindow();
    // resize窗口
    window.onresize = function () {
        resizeWindow();
    };

    var modelOrigin = parent.document.getElementById('modelOrigin').value;
    var fileUploadOrigin = parent.document.getElementById('fileUploadOrigin').value;

     //获取用户名
    // function GetUserNO() {
    //     var thisresult = null;
    //     $.ajax({
    //         type: "post",
    //         async: false,
    //         url: "/BaseAshx/User/UserManage.ashx",
    //         data: {
    //             mtype: "GetUserNo"
    //         },
    //         datatype: "json",
    //         success: function(result) {
    //             thisresult = result;
    //         },
    //         error: function(err) {
    //             if (err.status == 405)
    //                 top.location.href = '/';
    //         }
    //     })
    //     return thisresult;
    // }
    // var userno = GetUserNO() || 'userno'; 
    var userno = getCookie('portaluserno') || 'userno'; 
    

    function getList() {
        //return;
        $.ajax({
            type: 'get',
            async: true,
            url: modelOrigin + '/sw/gpTask/jobMessageList',
            data: {
                userno: userno
            },
            datatype: 'json',
            success: function (res) {
                if (typeof res == 'string') {
                    res = JSON.parse(res);
                }
                if (res.code == 200) {
                    var html = '';
                    res.data.map(function (item, index) {
                        var jobId = item.jobId;
                        var modelId = item.id;
                        var modelName = item.modelName;
                        var module = item.module;
                        var username = item.username;
                        var jobStatus = item.jobStatus;
                        var fileName = item.fileName;
                        var contentDetail = item.contentDetail;

                        var TB_DATAEXPLORE_ID = item.TB_DATAEXPLORE_ID;
                        var dbname = item.dbname || '';
                        if (item.sdeName) {
                            var tablename = item.sdeName.split(',')[0] || '';
                        }

                        // 1 gp, 2 ga
                        var type = item.type;

                        var progress = false;
                        var jobStatusText;
                        var textColor;

                        switch (jobStatus) {
                            case 'esriJobSucceeded':
                                jobStatusText = '成功';
                                textColor = '#75b85f';
                                progress = true;
                                break;
                            case 'esriJobExecuting':
                                jobStatusText = '运行中';
                                // textColor = '#888';
                                textColor = 'rgb(243,87,161)';
                                break;
                            case 'esriJobFailed':
                                jobStatusText = '失败';
                                textColor = 'orange';
                                break;
                            case 'esriJobSubmitted':
                                jobStatusText = '运行中';
                                // textColor = '#888';
                                textColor = 'rgb(243,87,161)';
                                break;
                            default:
                                jobStatusText = '失败';
                                textColor = 'orange';
                                break;
                        }

                        var canDig = true;

                        html += `
                            <tr contentDetail='` + contentDetail + `' type="` + type + `" align="center" TB_DATAEXPLORE_ID="` + TB_DATAEXPLORE_ID + `" modelName="` + modelName + `" module="` + module + `" dbname="` + dbname + `" tablename="` + tablename + `" modelId="` + modelId + `" fileName="` + fileName + `" jobId="` + jobId + `" progress="` + progress + `" canDig="` + canDig + `">
                                <td class="ellipsis" title="` + modelName + `">` + modelName + `</td>
                                <td style="width:100px">` + module + `</td>
                                <td style="width:100px">` + username + `</td>
                                <td style="width:100px; font-weight: bolder; color:` + textColor + `">` +
                            jobStatusText +
                            // `<div class="skillbar">
                            //     <div class="filled` + (item.progress == 100 ? ` finish` : ``) + `" data-width="` + item.progress + `%" style="width: ` + item.progress + `%;">
                            //     </div>
                            //     <span class="percent">` + item.progress + `%</span>
                            // </div>` +
                            `</td>
                            </tr>
                            `;
                    });

                    $('#userTable').html(html);
                } else {
                    alert(res.msg);
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
    setTimeout(function ()  {
        getList();
    }, 0);
    // 10秒请求一次
    // setInterval(function () {
    //     getList();
    // }, 10000);

    // 用户名 姓名 部门 职务
    // var data = {
    //     pageTotal: 10,
    //     pageAmount: 10,
    //     dataTotal: 100,
    //     curPage: 1
    // };
    // new Page({
    //     id: 'pagination',
    //     pageTotal: data.pageTotal, //必填,总页数（最少1页）
    //     pageAmount: data.pageAmount, //每页多少条
    //     dataTotal: data.dataTotal, //总共多少条数据（至少1条）
    //     curPage: data.curPage, //初始页码,不填默认为1
    //     pageSize: data.pageSize, //分页个数,不填默认为5
    //     showPageTotalFlag: true, //是否显示数据统计,不填默认不显示
    //     showSkipInputFlag: true, //是否支持跳转,不填默认不显示
    //     getPage: function (page) {
    //         //获取当前页数
    //         //console.log('当前是第' + page + '页');
    //         data.curPage = page;
    //         var start = (page - 1) * data.pageAmount + 1;
    //         var end = page * data.pageAmount;
    //         //console.log(start, end);
    //         // 请求数据
    //         check(pickChoice, start, end, function (result) {
    //             refreshTable(result.data);
    //         });
    //     }
    // });

    // 选中(要根据用户判断按钮权限)
    $('#userTable').on('click', 'tr', function (e) {
        var $currentTarget = $(e.currentTarget);

        if ($currentTarget.hasClass('curSelectedNode')) {
            $currentTarget.removeClass('curSelectedNode');
            // $('#refreshBtn').addClass('unable');
            $('#showDetailBtn, #downloadBtn, #showResult, #excavateBtn').addClass('unable');
        } else {
            $('#userTable .curSelectedNode').removeClass('curSelectedNode');
            $currentTarget.addClass('curSelectedNode');
            // if (JSON.parse($currentTarget.attr('canDig'))) {
            //     $('#excavateBtn').removeClass('unable');
            // }

            var type = $currentTarget.attr('type');
            if (type == '1') {
                $('#downloadBtn, #excavateBtn').show();
            } else if (type == '2') {
                $('#downloadBtn, #excavateBtn').hide();
            } else if (type == '3') {
                $('#excavateBtn').hide();
            }

            // 成功
            if ($currentTarget.attr('progress') == 'true') {
                // if ($currentTarget.attr('type') !== '1') {
                //     $('#showResult').addClass('unable');
                // } else {
                //     $('#showResult').removeClass('unable');
                // }
                $('#showResult').removeClass('unable');
                // if ($currentTarget.attr('type') == '1') {
                //     $('#showResult').addClass('unable');
                // } else {
                //     $('#showResult').removeClass('unable');
                // }

                if ($currentTarget.attr('fileName') != 'undefined') {
                    $('#downloadBtn').removeClass('unable');
                } else {
                    $('#downloadBtn').addClass('unable');
                }
                $('#excavateBtn').removeClass('unable');
            } else {
                $('#showResult').addClass('unable');
                $('#downloadBtn').addClass('unable');
                $('#excavateBtn').addClass('unable');
            }
            $('#showDetailBtn').removeClass('unable');
        }
    });

    // 点击查看详情
    $('#showDetailBtn').on('click', function () {
        var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        // var html = `
        // <div id = "detailDiv">
        //     <table class="userTable" border="0" cellspacing="0" cellpadding="0">
        //         <tbody><tr class="head" id="tableTh" align="center">
        //             <th>进程名称</th>
        //             <th>进程进度</th>
        //             <th>运行时间</th>
        //             <th>状态</th>
        //             <th>备注</th>
        //         </tr>
        //     </tbody></table>
        //     <div id="tableContentDiv">
        //         <table class="userTable" id="userTable" border="0" cellspacing="0" cellpadding="0">
        //             <tbody><tr align="center">
        //                 <td>我是进程名称</td>
        //                 <td>我是进程进度</td>
        //                 <td>52:48:45</td>
        //                 <td>进行中</td>
        //                 <td>备注</td>
        //             </tr>
        //             <tr align="center">
        //                 <td>我是进程名称</td>
        //                 <td>我是进程进度</td>
        //                 <td>52:48:45</td>
        //                 <td>进行中</td>
        //                 <td>备注</td>
        //             </tr>
        //         </tbody></table>
        //         <div id="pagination" class="pagination" style="margin: 10px 20px"></div>
        //     </div>
        // </div>`;
        var html = '<div id="detailDiv" style="margin: 20px;">' + $('#userTable .curSelectedNode').attr('contentDetail') + '</div>';
        var index = layer.open({
            type: 1,
            title: $('#userTable .curSelectedNode td').eq(0).html() + '-模型运行信息',
            content: html,
            area: ['400px', '300px'],
            shadeClose: true, //点击遮罩关闭
        });
        //弹出即全屏
        // layer.full(index);
    });

    //点击刷新(ok)
    $('#refreshBtn').on('click', function () {
        $('#userTable').html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;刷新中...');
        setTimeout(function () {
            getList();
        }, 100);
    });

    // 点击挖掘
    $('#excavateBtn').on('click', function () {
        if ($(this).hasClass('unable')) {
            return;
        }

        var id = $('#userTable .curSelectedNode').attr('tb_dataexplore_id');
        var dbname = $('#userTable .curSelectedNode').attr('dbname');
        var tablename = $('#userTable .curSelectedNode').attr('tablename');

        if (id) {
            var url = '/BasePlatform/SmartStatistics/BasicStaticsNew.html?isExcavate=true&id=' + id + '&dbname=' + dbname + '&tablename=' + tablename;
            window.parent.layer.open({
                type: 2,
                title: "分析结果",
                area: ['1000px', '670px'],
                fixed: false, //不固定
                maxmin: true,
                content: url,
                offset: "auto",
                shade:0
            });
            //$(parent.window.document).find('#fexplore').attr('src', url);
        }
        //$(parent.window.document).find('#header_tab4').click();
        //window.parent.parent.window.SelectHeaderMainTab(3);
    });

    String.prototype.endWith = function (endStr) {
        var d = this.length - endStr.length;
        return (d >= 0 && this.lastIndexOf(endStr) == d);
    };
    // 查看结果
    $('#showResult').on('click', function () {
        if ($(this).hasClass('unable')) {
            return;
        }

        //测试道路选址服务添加
        //var layerInfo = {"ORDERINDEX":"001","ATTR_A":"现状数据","ATTR_B":"","ATTR_C":"","ATTR_D":"","ID":"2","NAME":"道路选址","ALIAS":"PROV","GUID":"64C3908D03BD42aFa857BcDe55E3dc1e_002","URL":"http://localhost:6080/arcgis/rest/services/DLXZ/MapServer","POSITION":"111.623,45.370,6","PRJ":"EPSG:4326","SERVICETYPE":"tile","SOURCE":"tilearcgisrest","STATUS":"online","PARAMETERS":"","SERVERTYPE":"arcgis","STYLE":"","ISQUERY":"true","YEAR":"2020","ORDERINDEX1":"1","DATANUM":"","VISIBLE":true};
        //var layerHelp = parent.window.document.getElementById('fmap').contentWindow.LayerHelper(layerInfo);
        //var thisLayer = layerHelp.addLayer();
        //parent.window.document.getElementById('fmap').contentWindow.cesium.layer3DList["64C3908D03BD42aFa857BcDe55E3dc1e_002"].alpha = 0.85;
        //return;



        var jobId = $('.curSelectedNode').attr('jobId');
        var modelId = $('.curSelectedNode').attr('modelId');
        var modelName = $('.curSelectedNode').attr('modelName');
        var module = $('.curSelectedNode').attr('module');
        // var url = modelOrigin + '/sw/gpTask/jobJsonResult/' + jobId;
        // url更新为文件上传下载origin, uploadFile
        var url = fileUploadOrigin + '/sw/upload/jobJsonResult/' + jobId;
        var type = $('.curSelectedNode').attr('type');
        if (type == '1') {
            parent.window.document.getElementById('fmap').contentWindow.other_objectToGeometry({
                type: "url", // url json
                // object: "../../MapServer/Json/testPolygon.json"
                object: url,
                modelName: modelName
            });
        } else if (type == '2') {
            // ga
            var filename = $('.curSelectedNode').attr('filename');
            parent.window.document.getElementById('fmap').contentWindow.other_featureServerToGeometry({
                url: filename
            });
        } else if (type == '3') {
            var fileName = $('.curSelectedNode').attr('fileName');
            if (fileName != 'undefined') {
                var fileNameArr = fileName.split(',');
                fileNameArr.map(function (item, index) {
                    if (item) {
                        var url = fileUploadOrigin + '/sw/upload/soeDownload?name=' + item;
                        if (item.endWith('.PDF') || item.endWith('.pdf')) {
                            window.open('/scripts/pdfJs/web/viewer.html?file=' + encodeURIComponent(url), '_blank');
                        } else {
                            window.open('/BasePlatform/ModelDriven/showImg.html?file=' + encodeURIComponent(url), '_blank');
                        }
                    }
                });
            }

        }
    });

    // 点击下载(ok)
    $('#downloadBtn').on('click', function () {
        if ($(this).hasClass('unable')) {
            return;
        }
        var fileName = $('.curSelectedNode').attr('fileName');
        var type = $('.curSelectedNode').attr('type');
        var download = 'download';
        if (type == '3') {
            download = 'soeDownload';
        }
        if (fileName != 'undefined') {
            var fileNameArr = fileName.split(',');
            // alert('当前模型将要下载共计' + fileNameArr.length + '个文件');
            fileNameArr.map(function (item, index) {
                if (item) {
                    var url = fileUploadOrigin + '/sw/upload/' + download + '?name=' + item;
                    window.location.href = url;
                }
            });
        }
    });
});